<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
class OrderController extends Controller
{
    //
    public function info($oid)
    {
        $order = DB::table('orders') -> where('oid',$oid) -> first();
        // dd($res);
        $info = DB::table('orders_info') 
        ->select('orders_info.*','goods.goodsname','goods.price','goodspic')
        ->leftJoin('goods','goods.gid','=','orders_info.gid')
        -> where('oid',$oid) 
        -> get();

        // dd($info);
        $sum = 0;
        foreach ($info as $key => $value) {
            $sum += $value -> scnt * $value -> price;
            // dd($value);
        }

        return view('admin.order.info',['order'=> $order,'info' => $info,'sum' => $sum,'title' => '详情']);
    }

    public function send($oid)
    {   
        $status = 2;
        $res = DB::table('orders') -> where('oid',$oid) ->update(['status' => $status]);
        if($res)
        {
            return redirect('/admin/order');
        }else
        {
            return back() -> with(['info' => '订单']);
        }
    }
    public function index(Request $request)
    {
       
        $num = $request -> input('num',10);
        $keywords = $request -> input('keywords','');
        $data = DB::table('orders')
        -> select('orders.*','addr.rec','addr.addr','addr.tel')
        -> leftJoin('addr','addr.id','=','orders.addrid')
        -> where('addr.rec','like','%'.$keywords.'%')
        // -> get()
        -> paginate($num);
        
        // dd($data);
        return view('admin.order.index',["title" => '订单','request' => $request->all(),'data' => $data]);
    }

     public function delete($oid)
    {
        DB::beginTransaction();
        try
        {   
            $res = DB::table('orders') -> where('oid',$oid) -> delete();
            if(!$res)
            {
                throw new Exception("Error Processing Request", 1);
            }
            $res2 = DB::table('orders_info') -> where('oid',$oid) -> delete();
            if(!$res2)
            {
                throw new Exception("Error Processing Request", 2);
            }
            DB::commit();
           
            return redirect('/admin/order');
        }catch (\Exception $e){
            DB::rollback();
            echo $e -> getMessage();
            echo $e -> getCode();
            return back() -> with(['info' => '删除失败']);
        }
    }
}
